﻿using System;
using System.Drawing;
using System.Windows.Forms;
using AyuBookmark.Common.Models;

namespace AyuBookmark.WinForm.Controls
{
    /// <summary>
    /// 书签列表项控件（用于VirtualListView）
    /// </summary>
    public class BookmarkItem : UserControl
    {
        private Bookmark _bookmark;
        private Label lblTitle;
        private Label lblUrl;
        private Label lblDescription;
        private PictureBox imgIcon;
        private Panel panelSeparator;
        private bool _isSelected;

        // 颜色配置
        private readonly Color NormalBackColor = Color.White;
        private readonly Color HoverBackColor = Color.FromArgb(240, 245, 250);
        private readonly Color SelectedBackColor = Color.FromArgb(225, 240, 255);
        private readonly Color SeparatorColor = Color.FromArgb(240, 240, 240);

        // 默认图标
        private readonly System.Drawing.Image DefaultFavicon;

        public BookmarkItem()
        {
            // 创建默认图标（实际项目应使用资源文件）
            DefaultFavicon = CreateDefaultFavicon();
            InitializeComponents();
            SetupEvents();
        }

        private System.Drawing.Image CreateDefaultFavicon()
        {
            // 动态生成一个简单的默认图标
            var bmp = new Bitmap(16, 16);
            using (var g = Graphics.FromImage(bmp))
            {
                g.Clear(Color.Transparent);
                g.FillEllipse(Brushes.Blue, 0, 0, 15, 15);
                g.DrawString("B", new Font("Arial", 8, FontStyle.Bold), Brushes.White, 4, 2);
            }
            return bmp;
        }

        /// <summary>
        /// 获取或设置关联的书签数据
        /// </summary>
        public Bookmark Bookmark
        {
            get => _bookmark;
            set
            {
                _bookmark = value;
                UpdateDisplay();
            }
        }

        /// <summary>
        /// 获取或设置选中状态
        /// </summary>
        public bool IsSelected
        {
            get => _isSelected;
            set
            {
                _isSelected = value;
                UpdateSelectionStyle();
            }
        }

        private void InitializeComponents()
        {
            // 基础设置
            this.SuspendLayout();
            this.BackColor = NormalBackColor;
            this.Margin = new Padding(0);
            this.Size = new Size(400, 80);

            // 图标区域
            this.imgIcon = new PictureBox();
            this.imgIcon.SizeMode = PictureBoxSizeMode.Zoom;
            this.imgIcon.Size = new Size(32, 32);
            this.imgIcon.Location = new Point(10, 15);
            this.imgIcon.BackColor = Color.Transparent;
            this.imgIcon.Image = DefaultFavicon;

            // 标题标签
            this.lblTitle = new Label();
            this.lblTitle.AutoSize = false;
            this.lblTitle.Font = new Font("Microsoft YaHei", 10f, FontStyle.Bold);
            this.lblTitle.Location = new Point(50, 10);
            this.lblTitle.Size = new Size(340, 20);
            this.lblTitle.TextAlign = ContentAlignment.MiddleLeft;

            // URL标签
            this.lblUrl = new Label();
            this.lblUrl.AutoSize = false;
            this.lblUrl.Font = new Font("Microsoft YaHei", 8f);
            this.lblUrl.ForeColor = Color.Gray;
            this.lblUrl.Location = new Point(50, 35);
            this.lblUrl.Size = new Size(340, 15);
            this.lblUrl.TextAlign = ContentAlignment.MiddleLeft;

            // 描述标签
            this.lblDescription = new Label();
            this.lblDescription.AutoSize = false;
            this.lblDescription.Font = new Font("Microsoft YaHei", 8f);
            this.lblDescription.ForeColor = Color.DimGray;
            this.lblDescription.Location = new Point(50, 50);
            this.lblDescription.Size = new Size(340, 20);
            this.lblDescription.TextAlign = ContentAlignment.MiddleLeft;

            // 分隔线
            this.panelSeparator = new Panel();
            this.panelSeparator.BackColor = SeparatorColor;
            this.panelSeparator.Height = 1;
            this.panelSeparator.Dock = DockStyle.Bottom;

            // 添加控件
            this.Controls.Add(this.imgIcon);
            this.Controls.Add(this.lblTitle);
            this.Controls.Add(this.lblUrl);
            this.Controls.Add(this.lblDescription);  // 修正：直接添加控件而非调用不存在的方法
            this.Controls.Add(this.panelSeparator);

            this.ResumeLayout(false);
        }

        private void SetupEvents()
        {
            // 鼠标交互事件
            this.MouseEnter += (s, e) =>
            {
                if (!_isSelected) this.BackColor = HoverBackColor;
            };

            this.MouseLeave += (s, e) =>
            {
                if (!_isSelected) this.BackColor = NormalBackColor;
            };

            // 点击事件冒泡
            foreach (Control control in this.Controls)
            {
                control.MouseEnter += (s, e) => this.OnMouseEnter(e);
                control.MouseLeave += (s, e) => this.OnMouseLeave(e);
                control.Click += (s, e) => this.OnClick(e);
            }
        }

        private void UpdateDisplay()
        {
            if (_bookmark == null) return;

            this.lblTitle.Text = _bookmark.Title ?? "无标题";
            this.lblUrl.Text = _bookmark.Url ?? "";
            this.lblDescription.Text = _bookmark.Description ?? "";

            // 加载网站图标（示例代码，实际需要实现图标缓存）
            try
            {
                var domain = new Uri(_bookmark.Url).Host;
                this.imgIcon.Image = GetFavicon(domain);
            }
            catch
            {
                this.imgIcon.Image = DefaultFavicon;
            }
        }

        private void UpdateSelectionStyle()
        {
            this.BackColor = _isSelected ? SelectedBackColor : NormalBackColor;
        }

        /// <summary>
        /// 获取网站图标（需自行实现缓存逻辑）
        /// </summary>
        private System.Drawing.Image GetFavicon(string domain)
        {
            // 实际项目应实现：
            // 1. 检查本地缓存
            // 2. 从网络获取
            // 3. 返回默认图标
            return DefaultFavicon;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            // 绘制选中状态边框
            if (_isSelected)
            {
                using (var pen = new Pen(Color.FromArgb(0, 120, 215), 2))
                {
                    e.Graphics.DrawRectangle(pen, 0, 0, this.Width - 1, this.Height - 1);
                }
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                DefaultFavicon?.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}